// 首页 - 全新设计
const app = getApp()

Page({
  data: {
    // 基础数据
    isLoading: true,
    isLoggedIn: true, // 默认设为true，直接进入主界面
    hasUserInfo: false,
    userInfo: null,
    canIUseGetUserProfile: false,
    todayDate: '',
    currentYear: new Date().getFullYear(),
    currentMonth: new Date().getMonth() + 1,
    
    // 状态数据
    currentPhase: '未知',
    statusTitle: '开始记录',
    statusSubtitle: '记录你的经期数据',
    mainNumber: '?',
    mainUnit: '天',
    progressPercent: 0,
    
    // 日历数据
    calendarDays: [],
    
    // 预测数据
    nextPeriodDate: '',
    nextOvulationDate: '',
    averageCycle: '',
    
    // 今日记录
    todayRecord: {
      flow_level: -1,
      symptoms: [],
      mood: [],
      notes: ''
    },
    
    // 健康提醒
    healthTip: '定期记录经期数据，帮助预测下次月经时间',

    // 隐藏游戏入口
    titleTapCount: 0,
    titleTapTimer: null,
    
    // 快速记录弹窗
    showQuickRecord: false,
    quickRecordType: '',
    quickFlowLevel: -1,
    quickSymptoms: {},
    quickMoods: {},
    
    // 选项数据
    flowLevels: [
      { text: '无', class: 'flow-none' },
      { text: '少量', class: 'flow-light' },
      { text: '中量', class: 'flow-medium' },
      { text: '大量', class: 'flow-heavy' },
      { text: '极多', class: 'flow-very-heavy' }
    ],
    commonSymptoms: ['头痛', '腹痛', '腰痛', '乳房胀痛', '恶心', '疲劳', '情绪波动'],
    commonMoods: ['开心', '平静', '焦虑', '烦躁', '悲伤', '兴奋', '疲惫'],

    // 动画状态
    calendarAnimating: false,
    currentPeriodStart: '',
    
    // 新增：用户登录状态提示
    showLoginTip: false,
    
    // 新增：日期选择相关
    showPeriodConfirm: false,
    selectedDate: '',
    selectedDateDisplay: ''
  },

  onLoad: function() {
    // 注册页面实例到全局，用于头像联动
    const app = getApp()
    app.globalData.homePageInstance = this

    // 判断环境是否支持 getUserProfile
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }

    this.checkLoginStatus()
  },

  onShow: function() {
    // 每次显示页面时，同步最新的用户信息
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo && !userInfo.isGuest) {
      this.setData({
        userInfo: userInfo,
        hasUserInfo: true
      })
    }

    // 标记需要恢复经期高亮，由fetchCycleData统一处理
    this.shouldRestorePeriod = true
  },

  onUnload: function() {
    // 清理页面实例引用
    const app = getApp()
    if (app.globalData.homePageInstance === this) {
      app.globalData.homePageInstance = null
    }
  },

  // 检查登录状态
  checkLoginStatus: function() {
    // 获取本地存储的用户信息
    const userInfo = wx.getStorageSync('userInfo')

    if (userInfo && !userInfo.isGuest) {
      console.log('从本地恢复用户登录状态:', userInfo)
      this.setData({
        userInfo: userInfo,
        hasUserInfo: true
      })
    } else {
      console.log('用户未登录，使用游客模式')
      this.setData({
        hasUserInfo: false,
        userInfo: {
          nickName: '点击登录',
          avatarUrl: '/images/img1.jpg'
        }
      })
    }
    
    // 直接初始化页面，不显示登录提示
    this.initPage()
  },



  // 获取用户信息 - 优化后的登录方法
  getUserProfile: function() {
    const that = this

    // 显示加载中
    wx.showLoading({
      title: '登录中...',
      mask: true
    })

    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        // 获取到用户信息
        const userInfo = res.userInfo

        // 如果用户昵称是"微信用户"，设置默认昵称
        if (!userInfo.nickName || userInfo.nickName.trim() === '' || userInfo.nickName === '微信用户') {
          userInfo.nickName = "起个喜欢的名字吧~"
        }

        // 如果用户头像是默认头像，使用默认头像
        if (this.isDefaultAvatar(userInfo.avatarUrl)) {
          userInfo.avatarUrl = '/images/img1.jpg'
        }

        // 调用云函数获取openid
        wx.cloud.callFunction({
          name: 'getOpenId',
          success: function(openidRes) {
            const openid = openidRes.result.openid

            // 将用户信息存入云数据库
            const db = wx.cloud.database()

            // 先查询该用户是否已存在
            db.collection('users').where({
              _openid: openid
            }).get().then(checkRes => {
              if (checkRes.data.length === 0) {
                // 新用户，添加到数据库
                const timestamp = new Date().getTime()
                db.collection('users').add({
                  data: {
                    nickName: userInfo.nickName,
                    avatarUrl: userInfo.avatarUrl,
                    avatarTimestamp: timestamp,
                    gender: userInfo.gender,
                    country: userInfo.country,
                    province: userInfo.province,
                    city: userInfo.city,
                    registerTime: db.serverDate(),
                    lastLoginTime: db.serverDate()
                  }
                }).then(() => {
                  // 添加时间戳到本地存储
                  userInfo.avatarTimestamp = timestamp
                  // 添加本地存储
                  wx.setStorageSync('userInfo', userInfo)
                  that.setData({
                    userInfo: userInfo,
                    hasUserInfo: true
                  })

                  // 刷新页面数据
                  that.fetchCycleData()

                  wx.hideLoading()
                  wx.showToast({
                    title: '登录成功',
                    icon: 'success'
                  })
                }).catch(err => {
                  console.error('添加用户失败:', err)
                  wx.hideLoading()
                  wx.showToast({
                    title: '登录失败',
                    icon: 'none'
                  })
                })
              } else {
                // 老用户，使用数据库中已有的信息
                that.handleExistingUser(checkRes.data[0], userInfo)
              }
            }).catch(err => {
              console.error('查询用户失败:', err)
              wx.hideLoading()
              wx.showToast({
                title: '登录失败',
                icon: 'none'
              })
            })
          },
          fail: function(err) {
            console.error('获取openid失败:', err)
            wx.hideLoading()
            wx.showToast({
              title: '登录失败',
              icon: 'none'
            })
          }
        })
      },
      fail: (res) => {
        console.log('用户拒绝授权:', res)
        wx.hideLoading()
        wx.showToast({
          title: '需要授权才能使用',
          icon: 'none'
        })
      }
    })
  },

  // 初始化页面
  initPage: function() {
    const today = new Date()

    this.setData({
      todayDate: this.formatDisplayDate(today)
    })

    this.generateCalendar()
    this.fetchCycleData()
  },

  // 刷新数据
  refreshData: function() {
    this.fetchCycleData()
  },

  // 获取周期数据
  fetchCycleData: function() {
    wx.showLoading({ title: '加载中...' })

    // 如果是登录用户，从云端获取数据
    if (this.data.hasUserInfo) {
      // 同时获取周期数据和经期周期信息
      Promise.all([
        wx.cloud.callFunction({
          name: 'getCycleData',
          data: {}
        }),
        wx.cloud.callFunction({
          name: 'getPeriodCycle',
          data: {
            year: this.data.currentYear,
            month: this.data.currentMonth
          }
        })
      ]).then(([cycleRes, periodRes]) => {
        console.log('获取周期数据:', cycleRes)
        console.log('获取经期周期:', periodRes)

        // 处理基础周期数据
        if (cycleRes.result.status === 'success') {
          this.processData(cycleRes.result.data)
        } else {
          this.generateDefaultData()
        }

        // 处理经期周期数据
        let hasPeriodFromCloud = false
        if (periodRes.result && periodRes.result.status === 'success' && periodRes.result.data && periodRes.result.data.hasCycle) {
          const periodData = periodRes.result.data
          console.log('恢复云端经期数据:', periodData)
          this.updateCalendarWithPeriod(periodData.periodDates, periodData.startDate)
          hasPeriodFromCloud = true
        }

        // 如果云端没有经期数据，且需要恢复经期高亮，则从本地恢复
        if (!hasPeriodFromCloud && this.shouldRestorePeriod) {
          console.log('云端无经期数据，尝试从本地恢复')
          this.restorePeriodFromLocal()
        }

        // 重置恢复标记
        this.shouldRestorePeriod = false

      }).catch(err => {
        console.error('获取云端数据失败，降级到本地数据:', err)
        this.loadLocalData()
      }).finally(() => {
        wx.hideLoading()
        this.setData({ isLoading: false })
      })
    } else {
      // 游客用户，直接从本地存储获取数据
      this.loadLocalData()
      wx.hideLoading()
      this.setData({ isLoading: false })
    }
  },

  // 加载本地数据（游客模式）
  loadLocalData: function() {
    console.log('从本地加载数据')

    // 生成默认数据
    this.generateDefaultData()

    // 从本地存储获取经期数据
    const localPeriodData = wx.getStorageSync('localPeriodData') || {}
    const currentMonthKey = `${this.data.currentYear}-${this.data.currentMonth}`
    const monthData = localPeriodData[currentMonthKey] || []

    // 恢复经期高亮
    if (monthData.length > 0) {
      console.log('恢复本地经期数据:', monthData)
      this.updateCalendarWithPeriod(monthData, monthData[0].date)
    }

    // 从本地存储获取今日记录
    const localRecords = wx.getStorageSync('localDailyRecords') || {}
    const today = this.formatDate(new Date())
    const todayRecord = localRecords[today] || {
      flow_level: -1,
      symptoms: [],
      mood: [],
      notes: ''
    }

    this.setData({
      todayRecord: todayRecord
    })

    // 重置恢复标记
    this.shouldRestorePeriod = false
  },

  // 从本地存储恢复经期数据
  restorePeriodFromLocal: function() {
    const localCurrentPeriod = wx.getStorageSync('currentPeriodStart')
    if (localCurrentPeriod) {
      console.log('从本地存储恢复经期开始日期:', localCurrentPeriod)
      this.recreatePeriodHighlight(localCurrentPeriod)
    }
  },

  // 恢复经期高亮（已废弃，由fetchCycleData统一处理）
  restorePeriodHighlight: function() {
    console.log('restorePeriodHighlight已废弃，由fetchCycleData统一处理经期恢复')
    // 这个方法已经不再使用，所有经期恢复逻辑都已经整合到fetchCycleData中
    // 保留此方法只是为了向后兼容，如果有其他地方调用
  },

  // 重新创建经期高亮（不保存数据）
  recreatePeriodHighlight: function(startDate) {
    console.log('重新创建经期高亮，开始日期:', startDate)

    const startDateObj = new Date(startDate)
    let periodDates = []

    // 生成连续5天的经期日期（包括开始日）
    for (let i = 0; i < 5; i++) {
      const periodDate = new Date(startDateObj)
      periodDate.setDate(startDateObj.getDate() + i)

      // 添加所有5天的日期，不限制当月（可以跨月）
      periodDates.push({
        date: this.formatDate(periodDate),
        day: i + 1, // 经期第几天
        intensity: 1 - (i * 0.15) // 颜色强度，从1到0.25
      })
    }

    // 只更新日历显示，不保存数据
    this.updateCalendarWithPeriod(periodDates, startDate)
  },

  // 处理数据
  processData: function(data) {
    const today = new Date()
    const todayStr = this.formatDate(today)
    
    // 处理状态信息
    let statusInfo = this.calculateStatus(data)
    
    // 处理日历数据
    let calendarDays = this.processCalendarData(data.calendarDays || [])
    
    // 处理预测数据
    let predictions = this.calculatePredictions(data)
    
    this.setData({
      ...statusInfo,
      calendarDays: calendarDays,
      todayRecord: data.todayRecord || this.data.todayRecord,
      ...predictions,
      currentYear: data.currentYear || this.data.currentYear,
      currentMonth: data.currentMonth || this.data.currentMonth
    })
  },

  // 计算状态信息
  calculateStatus: function(data) {
    const { cycleDay, daysUntilNext, cyclePhase } = data
    
    let statusInfo = {
      currentPhase: cyclePhase || '未知',
      progressPercent: 0
    }
    
    if (cycleDay > 0) {
      // 经期中
      statusInfo.statusTitle = '经期第' + cycleDay + '天'
      statusInfo.statusSubtitle = '注意休息，保持温暖'
      statusInfo.mainNumber = cycleDay
      statusInfo.mainUnit = '天'
      statusInfo.progressPercent = Math.min((cycleDay / 7) * 100, 100)
    } else if (daysUntilNext > 0) {
      // 非经期
      statusInfo.statusTitle = '距离下次月经'
      statusInfo.statusSubtitle = '保持健康的生活习惯'
      statusInfo.mainNumber = daysUntilNext
      statusInfo.mainUnit = '天'
      statusInfo.progressPercent = Math.max(100 - (daysUntilNext / 28) * 100, 0)
    } else {
      // 无数据
      statusInfo.statusTitle = '开始记录'
      statusInfo.statusSubtitle = '记录你的经期数据'
      statusInfo.mainNumber = '?'
      statusInfo.mainUnit = '天'
      statusInfo.progressPercent = 0
    }
    
    return statusInfo
  },

  // 处理日历数据
  processCalendarData: function(calendarDays) {
    const today = new Date()
    const todayStr = this.formatDate(today)

    return calendarDays.map(item => {
      if (!item.day) return item

      const dateStr = `${this.data.currentYear}-${this.data.currentMonth.toString().padStart(2, '0')}-${item.day.toString().padStart(2, '0')}`

      // 保持原有的经期信息
      let processedItem = {
        ...item,
        date: dateStr,
        hasRecord: item.hasRecord || false
      }

      // 如果有经期信息，保持经期类型和强度
      if (item.periodDay) {
        processedItem.periodDay = item.periodDay
        processedItem.intensity = item.intensity
        processedItem.type = item.type || `period${item.periodDay}`
      }

      return processedItem
    })
  },

  // 计算预测数据
  calculatePredictions: function(data) {
    return {
      nextPeriodDate: data.nextPeriodDate ? this.formatDisplayDate(new Date(data.nextPeriodDate)) : '',
      nextOvulationDate: data.ovulationDate ? this.formatDisplayDate(new Date(data.ovulationDate)) : '',
      averageCycle: data.averageCycle || ''
    }
  },

  // 生成默认数据
  generateDefaultData: function() {
    this.generateCalendar()
    
    // 根据登录状态设置不同的健康提醒
    const healthTip = this.data.hasUserInfo ? 
      '定期记录经期数据，帮助预测下次月经时间' : 
      '欢迎使用经期记录！数据保存在本地，登录后可同步到云端'
    
    this.setData({
      currentPhase: '未知',
      statusTitle: '开始记录',
      statusSubtitle: '点击日历日期记录经期数据',
      mainNumber: '?',
      mainUnit: '天',
      progressPercent: 0,
      nextPeriodDate: '',
      nextOvulationDate: '',
      averageCycle: '',
      healthTip: healthTip
    })
  },

  // 生成日历
  generateCalendar: function() {
    const { currentYear, currentMonth } = this.data
    const today = new Date()
    const daysInMonth = new Date(currentYear, currentMonth, 0).getDate()
    const firstDay = new Date(currentYear, currentMonth - 1, 1).getDay()
    
    // 获取当前已有的日历数据，保留经期状态
    const existingCalendarDays = this.data.calendarDays || []
    const existingPeriodData = {}
    
    // 保存现有的经期数据
    existingCalendarDays.forEach(item => {
      if (item.date && item.periodDay) {
        existingPeriodData[item.date] = {
          periodDay: item.periodDay,
          intensity: item.intensity,
          type: item.type
        }
      }
    })
    
    let calendarDays = []
    
    // 添加空白格
    for (let i = 0; i < firstDay; i++) {
      calendarDays.push({ day: '', type: 'empty' })
    }
    
    // 添加日期
    for (let day = 1; day <= daysInMonth; day++) {
      const date = new Date(currentYear, currentMonth - 1, day)
      const dateStr = this.formatDate(date)
      let type = ''

      // 标记未来日期
      if (date > today) {
        type = 'future'
      }

      // 检查是否有已保存的经期数据
      const savedPeriodData = existingPeriodData[dateStr]
      let dayItem = {
        day,
        date: dateStr,
        type,
        hasRecord: false
      }

      // 如果有经期数据，恢复它
      if (savedPeriodData) {
        dayItem.type = savedPeriodData.type
        dayItem.periodDay = savedPeriodData.periodDay
        dayItem.intensity = savedPeriodData.intensity
        console.log(`恢复日期 ${dateStr} 的经期状态:`, savedPeriodData)
      }

      calendarDays.push(dayItem)
    }
    
    console.log('生成日历时保留的经期数据数量:', Object.keys(existingPeriodData).length)
    this.setData({ calendarDays })
  },

  // 上个月
  prevMonth: function() {
    let { currentYear, currentMonth } = this.data
    
    if (currentMonth === 1) {
      currentYear -= 1
      currentMonth = 12
    } else {
      currentMonth -= 1
    }
    
    this.setData({ currentYear, currentMonth })
    // 隐藏确认条
    this.hidePeriodConfirmBar()
    // 重新生成日历并获取该月份的经期数据
    this.generateCalendar()
    this.loadMonthPeriodData()
  },

  // 下个月
  nextMonth: function() {
    let { currentYear, currentMonth } = this.data
    
    if (currentMonth === 12) {
      currentYear += 1
      currentMonth = 1
    } else {
      currentMonth += 1
    }
    
    this.setData({ currentYear, currentMonth })
    // 隐藏确认条
    this.hidePeriodConfirmBar()
    // 重新生成日历并获取该月份的经期数据
    this.generateCalendar()
    this.loadMonthPeriodData()
  },

  // 点击日期
  onDayTap: function(e) {
    const { day, date } = e.currentTarget.dataset

    if (!day) return

    // 检查是否是未来日期
    const selectedDate = new Date(date)
    const today = new Date()
    today.setHours(23, 59, 59, 999)

    if (selectedDate > today) {
      wx.showToast({
        title: '不能选择未来日期',
        icon: 'none'
      })
      return
    }

    // 显示底部确认区域
    this.showPeriodConfirmBar(date, day)
  },

  // 显示底部月经确认条
  showPeriodConfirmBar: function(date, day) {
    const selectedDate = new Date(date)
    const month = selectedDate.getMonth() + 1
    const dayNum = selectedDate.getDate()

    this.setData({
      showPeriodConfirm: true,
      selectedDate: date,
      selectedDateDisplay: `${month}月${dayNum}日`
    })
  },

  // 隐藏确认条
  hidePeriodConfirmBar: function() {
    this.setData({
      showPeriodConfirm: false,
      selectedDate: '',
      selectedDateDisplay: ''
    })
  },

  // 确认月经来了
  confirmPeriodYes: function() {
    const selectedDate = this.data.selectedDate
    if (selectedDate) {
      this.setPeriodStart(selectedDate)
      this.hidePeriodConfirmBar()
    }
  },

  // 确认月经没来
  confirmPeriodNo: function() {
    const selectedDate = this.data.selectedDate
    if (selectedDate) {
      this.removePeriodHighlight(selectedDate)
      this.hidePeriodConfirmBar()
    }
  },

  // 阻止事件冒泡
  preventBubble: function() {
    // 空方法，用于阻止事件冒泡
  },

  // 加载指定月份的经期数据
  loadMonthPeriodData: function() {
    if (this.data.hasUserInfo) {
      // 登录用户，从云端获取该月份的经期数据
      wx.cloud.callFunction({
        name: 'getPeriodCycle',
        data: {
          year: this.data.currentYear,
          month: this.data.currentMonth
        }
      }).then(res => {
        console.log('获取月份经期数据:', res)
        if (res.result && res.result.status === 'success' && res.result.data && res.result.data.hasCycle) {
          const periodData = res.result.data
          console.log('恢复该月份经期数据:', periodData)
          this.updateCalendarWithPeriod(periodData.periodDates, periodData.startDate)
        }
      }).catch(err => {
        console.error('获取月份经期数据失败:', err)
      })
    } else {
      // 游客用户，从本地存储获取该月份的经期数据
      const localPeriodData = wx.getStorageSync('localPeriodData') || {}
      const currentMonthKey = `${this.data.currentYear}-${this.data.currentMonth}`
      const monthData = localPeriodData[currentMonthKey] || []

      if (monthData.length > 0) {
        console.log('恢复本地月份经期数据:', monthData)
        this.updateCalendarWithPeriod(monthData, monthData[0].date)
      }
    }
  },

  // 设置月经开始
  setPeriodStart: function(startDate) {
    console.log('用户确认月经来了，日期:', startDate)

    // 不立即高亮，先询问是否创建新周期
    this.askCreateNewCycle(startDate)
  },

  // 移除经期高亮
  removePeriodHighlight: function(date) {
    // 移除所有经期标记（清空整个月的经期数据）
    this.clearAllPeriodMarks()

    // 从云端删除本月所有经期记录
    this.removeAllPeriodData()
  },

  // 清空所有经期标记
  clearAllPeriodMarks: function() {
    let calendarDays = [...this.data.calendarDays]

    calendarDays.forEach((item) => {
      if (item.date) {
        // 移除所有经期相关的类名，保留其他类名（如future）
        let newType = item.type.replace(/period\d*/g, '').replace(/\s+/g, ' ').trim()

        item.type = newType
        delete item.periodDay
        delete item.intensity
      }
    })

    this.setData({
      calendarDays: calendarDays,
      currentPeriodStart: ''
    })

    // 清除本地存储的经期数据
    wx.removeStorageSync('currentPeriodStart')

    if (this.data.hasUserInfo) {
      // 登录用户，删除云端经期周期数据
      wx.cloud.callFunction({
        name: 'deletePeriodCycle',
        data: {
          year: this.data.currentYear,
          month: this.data.currentMonth
        }
      }).then(res => {
        console.log('云端经期周期删除结果:', res)
      }).catch(err => {
        console.error('删除云端经期周期失败:', err)
      })
    } else {
      // 游客模式，清除本地经期数据
      const localPeriodData = wx.getStorageSync('localPeriodData') || {}
      const currentMonthKey = `${this.data.currentYear}-${this.data.currentMonth}`
      delete localPeriodData[currentMonthKey]
      wx.setStorageSync('localPeriodData', localPeriodData)
    }

    // 触发动画
    this.animateCalendarUpdate()
  },

  // 更新日历显示经期
  updateCalendarWithPeriod: function(periodDates, startDate) {
    console.log('更新日历显示经期，经期数据:', periodDates)
    console.log('当前日历数据:', this.data.calendarDays.slice(0, 5))

    let calendarDays = [...this.data.calendarDays]
    let updatedCount = 0

    calendarDays.forEach((item) => {
      if (item.date) {
        // 先清除之前的经期标记，但保留其他类名（如future）
        let baseType = item.type.replace(/period\d*/g, '').replace(/\s+/g, ' ').trim()

        // 检查是否是新的经期日期
        const periodInfo = periodDates.find(p => p.date === item.date)
        if (periodInfo) {
          // 添加经期类名
          item.type = baseType ? `${baseType} period${periodInfo.day}` : `period${periodInfo.day}`
          item.periodDay = periodInfo.day
          item.intensity = periodInfo.intensity
          updatedCount++
          console.log(`更新日期 ${item.date} 为经期第${periodInfo.day}天，类型: ${item.type}`)
        } else {
          // 不是经期日期，保持原有类名
          item.type = baseType
          delete item.periodDay
          delete item.intensity
        }
      }
    })

    console.log(`总共更新了 ${updatedCount} 个日期`)

    this.setData({
      calendarDays: calendarDays,
      currentPeriodStart: startDate
    })

    // 保存经期开始日期到本地存储（用于页面切换恢复）
    wx.setStorageSync('currentPeriodStart', startDate)

    console.log('设置数据后的日历:', this.data.calendarDays.filter(item => item.periodDay))

    // 触发动画
    this.animateCalendarUpdate()
  },

  // 删除所有经期数据
  removeAllPeriodData: function() {
    wx.showLoading({ title: '删除中...' })

    // 获取当前月份的所有日期
    const { currentYear, currentMonth } = this.data
    const daysInMonth = new Date(currentYear, currentMonth, 0).getDate()
    let datesToDelete = []

    for (let day = 1; day <= daysInMonth; day++) {
      const date = new Date(currentYear, currentMonth - 1, day)
      datesToDelete.push(this.formatDate(date))
    }

    const promises = datesToDelete.map(dateStr => {
      return wx.cloud.callFunction({
        name: 'deleteDailyRecord',
        data: { date_str: dateStr }
      })
    })

    Promise.all(promises).then(() => {
      wx.hideLoading()
      wx.showToast({
        title: '经期记录已清除',
        icon: 'success'
      })
    }).catch(err => {
      wx.hideLoading()
      console.error('删除经期数据失败:', err)
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      })
    })
  },

  // 日历更新动画
  animateCalendarUpdate: function() {
    // 添加更新动画类
    this.setData({ calendarAnimating: true })

    // 300ms后移除动画类
    setTimeout(() => {
      this.setData({ calendarAnimating: false })
    }, 300)
  },

  // 快速记录经期
  quickRecordPeriod: function() {
    this.setData({
      showQuickRecord: true,
      quickRecordType: 'period',
      quickFlowLevel: this.data.todayRecord.flow_level >= 0 ? this.data.todayRecord.flow_level : 1
    })
  },

  // 快速记录症状
  quickRecordSymptom: function() {
    let quickSymptoms = {}
    this.data.todayRecord.symptoms.forEach(symptom => {
      quickSymptoms[symptom] = true
    })

    this.setData({
      showQuickRecord: true,
      quickRecordType: 'symptom',
      quickSymptoms
    })
  },

  // 快速记录心情
  quickRecordMood: function() {
    let quickMoods = {}
    this.data.todayRecord.mood.forEach(mood => {
      quickMoods[mood] = true
    })

    this.setData({
      showQuickRecord: true,
      quickRecordType: 'mood',
      quickMoods
    })
  },

  // 打开详细记录
  openDetailRecord: function() {
    const today = this.formatDate(new Date())
    wx.navigateTo({
      url: `/pages/record/record?date=${today}`
    })
  },

  // 工具方法
  formatDate: function(date) {
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${year}-${month}-${day}`
  },

  formatDisplayDate: function(date) {
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${month}月${day}日`
  },

  // 快速记录相关方法
  closeQuickRecord: function() {
    this.setData({
      showQuickRecord: false,
      quickRecordType: '',
      quickFlowLevel: -1,
      quickSymptoms: {},
      quickMoods: {}
    })
  },

  selectFlowLevel: function(e) {
    const level = e.currentTarget.dataset.level
    this.setData({ quickFlowLevel: level })
  },

  toggleSymptom: function(e) {
    const symptom = e.currentTarget.dataset.symptom
    const key = `quickSymptoms.${symptom}`
    this.setData({
      [key]: !this.data.quickSymptoms[symptom]
    })
  },

  toggleMood: function(e) {
    const mood = e.currentTarget.dataset.mood
    const key = `quickMoods.${mood}`
    this.setData({
      [key]: !this.data.quickMoods[mood]
    })
  },

  saveQuickRecord: function() {
    const today = this.formatDate(new Date())
    let recordData = {
      date_str: today,
      flow_level: -1,
      symptoms: [],
      mood: [],
      notes: ''
    }

    // 根据记录类型收集数据
    if (this.data.quickRecordType === 'period') {
      recordData.flow_level = this.data.quickFlowLevel
    } else if (this.data.quickRecordType === 'symptom') {
      recordData.symptoms = Object.keys(this.data.quickSymptoms).filter(key => this.data.quickSymptoms[key])
    } else if (this.data.quickRecordType === 'mood') {
      recordData.mood = Object.keys(this.data.quickMoods).filter(key => this.data.quickMoods[key])
    }

    // 保留现有的其他数据
    if (this.data.todayRecord) {
      if (this.data.quickRecordType !== 'period') {
        recordData.flow_level = this.data.todayRecord.flow_level
      }
      if (this.data.quickRecordType !== 'symptom') {
        recordData.symptoms = this.data.todayRecord.symptoms || []
      }
      if (this.data.quickRecordType !== 'mood') {
        recordData.mood = this.data.todayRecord.mood || []
      }
      recordData.notes = this.data.todayRecord.notes || ''
    }

    wx.showLoading({ title: '保存中...' })

    // 检查是否为登录用户
    if (this.data.hasUserInfo) {
      // 登录用户，保存到云端
      wx.cloud.callFunction({
        name: 'saveDailyRecord',
        data: {
          recordId: '',
          recordData: recordData
        }
      }).then(res => {
        this.handleSaveSuccess(recordData)
      }).catch(err => {
        console.error('云端保存失败，降级到本地保存:', err)
        this.saveToLocal(recordData)
      })
    } else {
      // 游客用户，保存到本地
      this.saveToLocal(recordData)
    }
  },

  // 处理保存成功
  handleSaveSuccess: function(recordData) {
    wx.hideLoading()
    wx.showToast({
      title: '保存成功',
      icon: 'success'
    })

    this.closeQuickRecord()
    this.refreshData()

    // 如果是经期记录且是新的经期开始，询问是否创建新周期
    if (this.data.quickRecordType === 'period' &&
        this.data.quickFlowLevel > 0 &&
        (!this.data.todayRecord || this.data.todayRecord.flow_level < 0)) {
      if (this.data.hasUserInfo) {
        this.askCreateNewCycle()
      } else {
        this.askCreateNewCycle(recordData.date_str)
      }
    }
  },

  // 保存到本地
  saveToLocal: function(recordData) {
    try {
      // 获取本地记录数据
      const localRecords = wx.getStorageSync('localDailyRecords') || {}
      localRecords[recordData.date_str] = recordData
      wx.setStorageSync('localDailyRecords', localRecords)

      this.handleSaveSuccess(recordData)
    } catch (err) {
      wx.hideLoading()
      console.error('本地保存失败:', err)
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      })
    }
  },

  askCreateNewCycle: function() {
    wx.showModal({
      title: '新周期',
      content: '检测到您标记了经期，是否将今天设为新周期的开始日？',
      success: (res) => {
        if (res.confirm) {
          this.createNewCycle()
        }
      }
    })
  },

  createNewCycle: function() {
    const today = this.formatDate(new Date())

    wx.showLoading({ title: '创建中...' })

    wx.cloud.callFunction({
      name: 'createCycle',
      data: {
        startDate: today
      }
    }).then(res => {
      wx.hideLoading()

      if (res.result.status === 'success') {
        wx.showToast({
          title: '新周期已创建',
          icon: 'success'
        })
        this.refreshData()
      } else {
        wx.showToast({
          title: '创建失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.hideLoading()
      console.error('创建周期失败:', err)
      wx.showToast({
        title: '创建失败',
        icon: 'none'
      })
    })
  },

  showSettings: function() {
    wx.showToast({
      title: '设置功能开发中',
      icon: 'none'
    })
  },

  // 隐藏游戏入口 - 标题点击事件
  onTitleTap: function() {
    this.data.titleTapCount++;

    // 清除之前的定时器
    if (this.data.titleTapTimer) {
      clearTimeout(this.data.titleTapTimer);
    }

    // 设置新的定时器，2秒后重置计数
    this.data.titleTapTimer = setTimeout(() => {
      this.setData({ titleTapCount: 0 });
    }, 2000);

    // 连续点击5次进入隐藏游戏
    if (this.data.titleTapCount >= 5) {
      this.setData({ titleTapCount: 0 });
      if (this.data.titleTapTimer) {
        clearTimeout(this.data.titleTapTimer);
      }

      wx.showToast({
        title: '发现隐藏游戏！',
        icon: 'success',
        duration: 1500
      });

      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/block_game/block_game'
        });
      }, 1500);
    } else if (this.data.titleTapCount >= 3) {
      // 点击3次以上给提示
      wx.showToast({
        title: `再点击${5 - this.data.titleTapCount}次...`,
        icon: 'none',
        duration: 800
      });
    }
  },

  // 头像点击事件 - 登录或编辑用户信息
  onAvatarTap: function() {
    if (this.data.hasUserInfo) {
      // 已登录用户，编辑用户信息
      this.editUserInfo()
    } else {
      // 未登录用户，提示登录
      wx.showModal({
        title: '登录微信账号',
        content: '登录后数据将安全保存到云端，避免数据丢失',
        confirmText: '立即登录',
        cancelText: '继续使用',
        confirmColor: '#A06CD5',
        success: (res) => {
          if (res.confirm) {
            this.getUserProfile()
          }
        }
      })
    }
  },

  // 处理老用户登录
  handleExistingUser: function(dbUserInfo, wechatUserInfo) {
    const that = this
    const userId = dbUserInfo._id
    const db = wx.cloud.database()

    // 更新或使用现有时间戳
    const timestamp = dbUserInfo.avatarTimestamp || new Date().getTime()

    // 确定要使用的昵称
    let finalNickName
    if (dbUserInfo.nickName && dbUserInfo.nickName !== '微信用户') {
      finalNickName = dbUserInfo.nickName
    } else if (wechatUserInfo.nickName && wechatUserInfo.nickName !== '微信用户') {
      finalNickName = wechatUserInfo.nickName
    } else {
      finalNickName = "起个喜欢的名字吧~"
    }

    // 确定要使用的头像
    let finalAvatarUrl
    if (dbUserInfo.avatarUrl && !this.isDefaultAvatar(dbUserInfo.avatarUrl)) {
      finalAvatarUrl = dbUserInfo.avatarUrl
    } else if (wechatUserInfo.avatarUrl && !this.isDefaultAvatar(wechatUserInfo.avatarUrl)) {
      finalAvatarUrl = wechatUserInfo.avatarUrl
    } else {
      finalAvatarUrl = '/images/img1.jpg'
    }

    // 更新登录时间，保留用户自定义的昵称和头像
    db.collection('users').doc(userId).update({
      data: {
        lastLoginTime: db.serverDate(),
        gender: wechatUserInfo.gender,
        country: wechatUserInfo.country,
        province: wechatUserInfo.province,
        city: wechatUserInfo.city,
        nickName: finalNickName,
        avatarUrl: finalAvatarUrl,
        avatarTimestamp: timestamp
      }
    }).then(() => {
      // 构建最终的用户信息
      const finalUserInfo = {
        nickName: finalNickName,
        avatarUrl: finalAvatarUrl,
        avatarTimestamp: timestamp,
        gender: wechatUserInfo.gender,
        country: wechatUserInfo.country,
        province: wechatUserInfo.province,
        city: wechatUserInfo.city
      }

      // 保存到本地存储
      wx.setStorageSync('userInfo', finalUserInfo)
                        that.setData({
                    userInfo: finalUserInfo,
                    hasUserInfo: true
                  })

                  // 刷新页面数据
                  that.fetchCycleData()

                  wx.hideLoading()
                  wx.showToast({
                    title: '登录成功',
                    icon: 'success'
                  })
    }).catch(err => {
      console.error('更新用户信息失败:', err)
      wx.hideLoading()
      wx.showToast({
        title: '登录失败',
        icon: 'none'
      })
    })
  },

  // 判断是否为默认头像
  isDefaultAvatar: function(avatarUrl) {
    if (!avatarUrl) return true

    // 微信默认头像的特征
    const defaultPatterns = [
      'thirdwx.qlogo.cn',
      '/132',  // 微信默认头像通常包含这个路径
      'wx.qlogo.cn'
    ]

    return defaultPatterns.some(pattern => avatarUrl.includes(pattern))
  },

  // 编辑用户信息
  editUserInfo: function() {
    wx.showModal({
      title: '个人信息',
      content: `昵称：${this.data.userInfo.nickName}\n\n点击确定可以修改昵称`,
      confirmText: '修改昵称',
      cancelText: '取消',
      confirmColor: '#A06CD5',
      success: (res) => {
        if (res.confirm) {
          this.editNickname()
        }
      }
    })
  },

  // 修改昵称
  editNickname: function() {
    const currentNickname = this.data.userInfo.nickName
    const placeholder = currentNickname === '起个喜欢的名字吧~' ? '请输入你的昵称' : currentNickname

    wx.showModal({
      title: '修改昵称',
      content: '请输入新的昵称',
      editable: true,
      placeholderText: placeholder,
      confirmColor: '#A06CD5',
      success: (res) => {
        if (res.confirm && res.content.trim()) {
          const newNickname = res.content.trim()
          this.updateUserInfo({ nickName: newNickname })
        }
      }
    })
  },

  // 更新用户信息
  updateUserInfo: function(updateData) {
    wx.showLoading({ title: '更新中...' })

    wx.cloud.callFunction({
      name: 'updateUserInfo',
      data: updateData
    }).then(res => {
      wx.hideLoading()

      if (res.result.status === 'success') {
        // 更新本地用户信息
        const newUserInfo = { ...this.data.userInfo, ...updateData }

        // 同时更新云端用户信息
        const cloudUserInfo = wx.getStorageSync('cloudUserInfo') || {}
        const newCloudUserInfo = { ...cloudUserInfo, ...updateData }

        // 保存到本地存储
        wx.setStorageSync('userInfo', newUserInfo)
        wx.setStorageSync('cloudUserInfo', newCloudUserInfo)

        // 更新页面状态
        this.setData({
          userInfo: newUserInfo
        })

        console.log('用户信息更新成功:', newUserInfo)

        wx.showToast({
          title: '更新成功',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: '更新失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.hideLoading()
      console.error('更新用户信息失败:', err)
      wx.showToast({
        title: '更新失败',
        icon: 'none'
      })
    })
  },

  // 保存经期数据
  savePeriodData: function(startDate, periodDates) {
    console.log('开始保存经期数据到云端')
    wx.showLoading({ title: '保存中...' })

    // 保存经期周期信息
    wx.cloud.callFunction({
      name: 'savePeriodCycle',
      data: {
        startDate: startDate,
        periodDates: periodDates,
        year: this.data.currentYear,
        month: this.data.currentMonth
      }
    }).then(res => {
      console.log('经期周期保存成功:', res)
      if (res.result && res.result.status === 'success') {
        // 同时为每一天创建详细记录
        return this.saveDailyPeriodRecords(periodDates)
      } else {
        throw new Error(res.result ? res.result.message : '保存周期失败')
      }
    }).then(() => {
      wx.hideLoading()
      wx.showToast({
        title: '经期记录已保存',
        icon: 'success'
      })
    }).catch(err => {
      wx.hideLoading()
      console.error('保存经期数据失败，降级到本地存储:', err)

      // 降级到本地存储
      this.saveLocalPeriodData(startDate, periodDates)

      wx.showToast({
        title: '已保存到本地',
        icon: 'success'
      })
    })
  },

  // 保存每日经期记录
  saveDailyPeriodRecords: function(periodDates) {
    const promises = periodDates.map(periodInfo => {
      return wx.cloud.callFunction({
        name: 'saveDailyRecord',
        data: {
          recordId: '',
          recordData: {
            date_str: periodInfo.date,
            flow_level: Math.max(0, 4 - periodInfo.day), // 第1天最多，第5天最少
            symptoms: [],
            mood: [],
            notes: `经期第${periodInfo.day}天`
          }
        }
      })
    })

    return Promise.all(promises).then(results => {
      console.log('每日记录保存结果:', results)
      const allSuccess = results.every(res => res.result.status === 'success')
      if (!allSuccess) {
        console.warn('部分每日记录保存失败，但周期信息已保存')
      }
      return results
    })
  },



  // 询问创建新周期（修改参数）
  askCreateNewCycle: function(startDate) {
    wx.showModal({
      title: '新周期',
      content: '是否将此次月经设为新周期的开始？',
      confirmColor: '#A06CD5',
      success: (res) => {
        if (res.confirm) {
          // 用户确认创建新周期，现在才高亮经期
          this.createPeriodHighlight(startDate)
          this.createNewCycleWithDate(startDate)
        }
        // 如果用户取消，则什么都不做（不高亮，不保存）
      }
    })
  },

  // 创建经期高亮显示
  createPeriodHighlight: function(startDate) {
    console.log('创建经期高亮显示，开始日期:', startDate)

    const startDateObj = new Date(startDate)
    let periodDates = []

    // 生成连续5天的经期日期（包括开始日）
    for (let i = 0; i < 5; i++) {
      const periodDate = new Date(startDateObj)
      periodDate.setDate(startDateObj.getDate() + i)

      // 添加所有5天的日期，不限制当月（可以跨月）
      periodDates.push({
        date: this.formatDate(periodDate),
        day: i + 1, // 经期第几天
        intensity: 1 - (i * 0.15) // 颜色强度，从1到0.25
      })
    }

    console.log('生成的经期日期:', periodDates)

    // 更新日历显示
    this.updateCalendarWithPeriod(periodDates, startDate)

    // 保存数据（云端或本地）
    if (this.data.hasUserInfo) {
      // 登录用户保存到云端
      this.savePeriodData(startDate, periodDates)
    } else {
      // 游客用户保存到本地
      this.saveLocalPeriodData(startDate, periodDates)
    }
  },

  // 保存本地经期数据（游客模式）
  saveLocalPeriodData: function(startDate, periodDates) {
    console.log('游客模式，保存经期数据到本地')

    const localPeriodData = wx.getStorageSync('localPeriodData') || {}
    const currentMonthKey = `${this.data.currentYear}-${this.data.currentMonth}`

    // 保存当月的经期数据
    localPeriodData[currentMonthKey] = periodDates

    wx.setStorageSync('localPeriodData', localPeriodData)

    // 保存当前经期开始日期到页面数据
    this.setData({
      currentPeriodStart: startDate
    })

    wx.showToast({
      title: '经期记录已保存到本地',
      icon: 'success'
    })

    console.log('本地经期数据已保存:', localPeriodData)
  },

  // 创建新周期（修改方法名）
  createNewCycleWithDate: function(startDate) {
    wx.showLoading({ title: '创建中...' })

    wx.cloud.callFunction({
      name: 'createCycle',
      data: {
        startDate: startDate
      }
    }).then(res => {
      wx.hideLoading()

      if (res.result.status === 'success') {
        wx.showToast({
          title: '新周期已创建',
          icon: 'success'
        })
        // 不刷新数据，保持当前的经期显示
        console.log('新周期创建成功，保持当前经期显示')
      } else {
        wx.showToast({
          title: '创建失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.hideLoading()
      console.error('创建周期失败:', err)
      wx.showToast({
        title: '创建失败',
        icon: 'none'
      })
    })
  }
})
